﻿using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
using log4net.Core;
using Crossroad.Utils;
using Crossroad.Utils.Extensions;
using Crossroad.Core.Data;
using Crossroad.Core.Exceptions;
using Crossroad.Core.Helper;
using Crossroad.Core.Models;
using Crossroad.System.Admin.Model;
using Crossroad.System.Admin.Const;

namespace Crossroad.System.Admin.Service.Impl
{
    /// <summary>
    /// 组织架构
    /// </summary>
    public class OrganizationService: Access<Organization>, IOrganizationService
    {
        public OrganizationService(
        )
        {
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        public Pagination<Organization> GetPaging(
            int pageIndex,
            int pageSize,
            Action<ISugarQueryable<Organization>> method,
			bool loadRelevantData = true
        )
        {
            var query =  db.Queryable<Organization>();
            method(query);
            var totalCount = 0;
            var page = new Pagination<Organization>
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
            };
            page.Records = query.ToPageList(page.PageIndex, page.PageSize, ref totalCount);
            page.TotalCount = totalCount;
			if(loadRelevantData)
				Load(page.Records);

            return page;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public  List<Organization> GetList(
            Action<ISugarQueryable<Organization>> method,
			bool loadRelevantData = true
        )
        {
            var query =  db.Queryable<Organization>();
            method(query);
            var list = query.ToList();
			if(loadRelevantData)
				Load(list);

            return list;
        }

        /// <summary>
        /// 字典数据返回
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public object GetDicList(
            Action<ISugarQueryable<Organization>> method
		)
        {
            var query =  db.Queryable<Organization>();
            method(query);
			var list = query.Select(m => new DicDom { label = m.name, value = m.id.ToString() }).ToArray();
            return list;
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="method"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public Organization GetEntity(
            Action<ISugarQueryable<Organization>> method,
			bool loadRelevantData = true
		)
        {
            var query =  db.Queryable<Organization>();
            method(query);
            Organization model = query.First();
            if (loadRelevantData)
                Load(model);

            return model;
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="loadRelevantData">是否加载关联数据</param>
        /// <returns></returns>
        public Organization GetEntity(int id, bool loadRelevantData = true)
        {
            Organization model = db.Queryable<Organization>().InSingle(id);
            if (loadRelevantData)
                Load(model);

            return model;
        }

        /// <summary>
        /// 根据id列表查询maps
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public Dictionary<int, Organization> GetMaps(List<int> idList)
        {
            var maps = new Dictionary<int, Organization>();
            if (idList.Count < 1)
                return maps;

            var list = db.Queryable<Organization>()
                .In(f => f.id, idList.Distinct().ToArray())
                .ToList();

            list.ForEach(m =>
            {
                maps.Add(m.id, m);
            });

            return maps;
        }

        /// <summary>
        /// 新增返回详情
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Organization CreateAt(Organization model)
        {
            model.parentId = model.parentId ?? 0;
            model.layerList = null;
            model.layerNum = null;
            model.createTime = DateTime.Now.ToTimeStamp();
            try
            {
                BeginTran();
                model = db.Insertable(model).ExecuteReturnEntity();

                if (model.parentId.NotContent())
                {
                    model.layerList = $",{model.id},";
                    model.layerNum = 1;
                }
                else
                {
                    var parent = GetEntity(model.parentId.Value, false);
                    model.layerList = $"{parent.layerList}{model.id},";
                    model.layerNum = model.layerList.DelLastComma().AppearaCount(',');
                }
                var rows = db.Updateable(model).UpdateColumns(f => new { f.layerList, f.layerNum }).ExecuteCommand();
                if (rows < 1)
                    throw new LogicException("修改layer id列表及深度失败！");

                CommitTran();
            }
            catch
            {
                RollbackTran();
            }

            return GetEntity(model.id);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
		public Organization UpdateAt(Organization model) 
		{
            var rows = db.Updateable(model).IgnoreColumns(true).ExecuteCommand();
            if (rows < 1)
                throw new LogicException("修改失败！");

            return GetEntity(model.id);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="source"></param>
        public void DeleteAt(Organization source)
        {
            BeginTran();
            try
            {
                var idList  = db.Queryable<Organization>().Where(a => SqlFunc.Contains(a.layerList, $",{source.id},")).Select(a => a.id).ToArray();
                var rows = db.Deleteable<Organization>().In(idList).ExecuteCommand();
                if (rows < 1)
                    throw new LogicException("删除失败！");
                CommitTran();
            }
            catch (Exception e)
            {
                RollbackTran();
                throw e;
            }
        }


		#region 加载关联数据

        public void Load(List<Organization> list)
        {
            if (list.IsNull())
                return;

            list.ForEach(model =>
            {
                if (model.parentId.NotContent())
                    model.parentName = "无";
                else
                    model.parentName = list.FirstOrDefault(f => f.parentId == model.parentId)?.name;
            });
        }

        public void Load(Organization model)
        {
            if (model.IsNull())
                return;
        }

        #endregion

        #region 业务逻辑

        #endregion

    }
}
